package davidlauzon.activerecord.manager;

import java.sql.SQLException;
import java.util.Vector;

import davidlauzon.activerecord.nodes.DeleteStatement;
import davidlauzon.activerecord.nodes.SqlStatement;
import davidlauzon.activerecord.nodes.Table;
import davidlauzon.activerecord.nodes.WhereClause;


public class DeleteManager extends StatementManager
{
    private DeleteStatement _statement;

    private Table          _table;
    private WhereClause    _whereClause;
    private String         _whereCondition;
    private Vector<Object> _whereArgs;
    
    public DeleteManager() {
        super();
    }
    
    public void reset() {
        super.reset();
       _table          = null;
       _whereClause    = null;
       _whereCondition = null;
       _whereArgs      = new Vector<Object>();
    }
    
    public DeleteManager from(Table from) {
        _table = from;
        setConnection(    _table.getConnection() );
        setSqlSerializer( _table.getConnection().getSerializer() );
        return this;
    }
    
    public DeleteManager where(String condition) {
        _whereCondition = condition;
        return this;
    }
    
    public DeleteManager _(Object unsafeValue) {
        _whereArgs.add( unsafeValue );
        return this;
    }
    
    @Override
    protected SqlStatement buildStatement() {
        Object[] args = null;
        if ( (_whereArgs != null) && (_whereArgs.size() > 0) )
            args = (Object[]) _whereArgs.toArray( new Object[_whereArgs.size()] );
        
        _whereClause = new WhereClause(_whereCondition, args);
        
        _statement = new DeleteStatement();
        _statement.setFrom(_table);
        _statement.setWhereClause(_whereClause);
        
        return _statement;
    }
    
    public int execute() throws SQLException {
        String sql = this.toSql();
        return getConnection().executeUpdate( sql );
    }
    
    public void executeLater() throws SQLException {
        String sql = this.toSql();
        getConnection().updateLater( sql );
    }
}
